<template>
  <div>
    <h1>商家来单提醒</h1>
    <div v-if="isConnected">
      <p>WebSocket 已连接。</p>
      <!-- 消息显示区域 -->
      <div id="messageArea">
        <div v-for="message in messages" :key="message.id">
          <p>{{ message.content }}</p>
        </div>
      </div>
      <!-- 隐藏的音频元素用于播放声音 -->
      <audio ref="audioPlayer" style="display:none;">
        <source src="../../../assets/preview.mp3" type="audio/mpeg">
      </audio>
    </div>
    <div v-else>
      <button @click="initWebSocket">连接WebSocket</button>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import { ElNotification } from 'element-plus';

export default {
  name: 'WebsocketDemo',
  setup() {
    const messages = ref([]);
    const isConnected = ref(false);
    let websocket = null;
    const audioPlayer = ref(null); // 引用 audio 元素

    const initWebSocket = () => {
      const socketUrl = 'ws://127.0.0.1:8085/ws/indentid';
      websocket = new WebSocket(socketUrl);

      websocket.onopen = () => {
        isConnected.value = true;
        console.log('WebSocket 连接成功');
      };

      websocket.onmessage = (event) => {
        const message = JSON.parse(event.data);
        messages.value.push(message);
        console.log(message)
        playAudio(); // 播放音频
        showNotification(message); // 显示通知
      };

      websocket.onerror = (error) => {
        console.error('WebSocket 出现错误:', error);
      };

      websocket.onclose = () => {
        isConnected.value = false;
        console.log('WebSocket 连接已关闭');
      };
    };

    const playAudio = () => {
      const player = audioPlayer.value;
      if (player) {
        player.currentTime = 0; // 重置到音频开始位置
        console.log('尝试播放音频...');
        // 手动触发播放
        player.play()
            .then(() => {
              console.log('音频播放成功');
            })
            .catch((error) => {
              console.error('音频播放失败:', error);
            });
      }
    };

    const showNotification = (message) => {
      ElNotification({
        title: '新订单提醒',
        message: `订单号：${message.OrderId}`,
        type: 'success',
        duration: 0,
        dangerouslyUseHTMLString: true,
      });
    };

    onMounted(() => {
      initWebSocket();
    });

    return {
      messages,
      isConnected,
      audioPlayer, // 将 audio 元素的引用暴露给模板
    };
  },
};
</script>

<style>
/* 你的 CSS 样式 */
#messageArea p {
  margin: 0;
  padding: 5px 0;
}
</style>